package pers.xiaoliang.concurrency.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import pers.xiaoliang.concurrency.example.immutable.RequestHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @version v1.0
 * @description: http过滤器
 * @author: xiaoliang.liu
 * @date: 2018/7/28 15:45
 */
@Slf4j
public class HttpFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        long threadId = Thread.currentThread().getId();

        // 打印访问者id和访问时间
        log.info("当前线程号：{} , {} 在 {} 访问了程序", threadId, request.getRemoteAddr(), DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        // 将线程id设置到ThreadLocal中
        RequestHolder.add(threadId);

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
